from django.contrib.auth import logout
from django.shortcuts import render, redirect
from django.views import View
from goods.models import GoodsChannel
from contents.models import ContentCategory

# Create your views here.
from meiduo_mall.utils.my_category import get_categories


class IndexView(View):

    def get(self, request):
        # categories = {}
        #
        # # 查询37个频道
        # channels = GoodsChannel.objects.order_by('sequence').all()
        #
        # for channel in channels:
        #     group_id = channel.group_id
        #     # 11个组 初始化字典数据
        #     if group_id not in categories:
        #         categories[group_id] = {
        #             'channels': [],
        #             'sub_cats': [],
        #         }
        #
        #     # 添加频道信息 37个频道
        #     # 一级分类
        #
        #     cat1 = channel.category
        #
        #     cat1_dict = {
        #         'url': channel.url,
        #         'name': cat1.name
        #     }
        #
        #     categories[group_id]['channels'].append(cat1_dict)
        #
        #     # 二级分类
        #     cats2 = cat1.subs.all()
        #     for cat2 in cats2:
        #         categories[group_id]['sub_cats'].append({
        #             'name': cat2.name,
        #             'subs': cat2.subs.all()
        #         })

        categories = get_categories()

        # 查询广告分类数据 25个
        content_categories = ContentCategory.objects.order_by('id').all()
        contents = {}
        for content_category in content_categories:
            contents[content_category.key] = content_category.content_set.all()

        print(categories)
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context=context)


class LogoutView(View):

    def get(self, request):
        # print(request.COOKIES)
        # 清除session
        logout(request)
        # 清除cookie
        response = redirect('/')
        # print(request.COOKIES)
        response.delete_cookie('username')
        # request.COOKIE['username'] = ''
        return response